import 'package:flutter/material.dart';
import 'package:sweet_app/bloc/application_bloc.dart';
import 'package:sweet_app/bloc/bloc_provider.dart';
import 'package:sweet_app/model/add_friend_history.dart';
import 'package:sweet_app/model/message_model.dart';
import 'package:sweet_app/pages/chat/chat_page.dart';
import 'package:sweet_app/pages/chat/history_model.dart';
import 'package:sweet_app/pages/test_page/test_list_page.dart';
import 'package:sweet_app/pages/widgets/common_list_widget.dart';
import 'package:sweet_app/pages/widgets/my_icon.dart';
import 'package:sweet_app/pages/widgets/pull_to_refresh_test.dart';
import 'package:sweet_app/pages/widgets/pull_to_refresh_test2.dart';
import 'package:uuid/uuid.dart';

class HistoryPage extends StatefulWidget {
  @override
  _HistoryPageState createState() => _HistoryPageState();
}

class _HistoryPageState extends State<HistoryPage> {
  List<HistoryModel> _data = [
    HistoryModel(friendName: "小A", lastMsg: "写代码吗", time: "10:02"),
    HistoryModel(friendName: "小D", lastMsg: "吃了？", time: "10:02"),
    HistoryModel(friendName: "小E", lastMsg: "吃了？", time: "10:02"),
  ];

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final ApplicationBloc appBloc = BlocProvider.of<ApplicationBloc>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("聊聊"),
        actions: <Widget>[
          StreamBuilder<List<AddHistory>>(
            builder: (context, snapshot) {
              final _historyItem = snapshot.data.isNotEmpty
                  ? snapshot.data.indexWhere((h) => !h.addFlag)
                  : null;
              print("builder: ${_historyItem}");
              return IconButton(
                icon: MyIcon(
                    icon: Icon(Icons.notifications_none),
                    color: _historyItem != null && _historyItem >= 0
                        ? Colors.redAccent
                        : null),
                onPressed: () {
                  Navigator.of(context)
                      .push(MaterialPageRoute(builder: (builder) {
                    return Scaffold(
                        appBar: AppBar(title: Text("新的朋友")),
                        body: CommonListWidget<AddHistory>(
                            (t) => ListTile(
                                title: Text(t.fId,
                                    overflow: TextOverflow.ellipsis),
                                subtitle: Text("${t.message}, time: ${t.time.toString()}",
                                    overflow: TextOverflow.ellipsis)),
                            snapshot.data));
                  }));
                },
              );
            },
            stream: appBloc.addHistoryStream,
            initialData: [],
          ),
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => DbTestPage()));
            },
          ),
        ],
      ),
      body: ListView.builder(
        itemExtent: 65.0,
        itemCount: _data.length,
        itemBuilder: (context, index) => HistoryItemWidget(
              historyModel: _data[index],
              onTap: () => _onTap(_data[index]),
            ),
      ),
    );
  }

  void _onTap(HistoryModel model) {
    Navigator.of(context).push(
        MaterialPageRoute(builder: (builder) => ChatPage(historyModel: model)));
  }
}

class DbTestPage extends StatefulWidget {
  @override
  _DbTestPageState createState() => _DbTestPageState();
}

class _DbTestPageState extends State<DbTestPage> {
  List<MessageModel> _list = [];

  @override
  Widget build(BuildContext context) {
    final ApplicationBloc applicationBloc =
        BlocProvider.of<ApplicationBloc>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("test db"),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: () => _onPressed(applicationBloc),
          )
        ],
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            FlatButton(
                onPressed: () {
                  applicationBloc.insertDb("""
                INSERT INTO t_messages 
                (id, type, content, toUser, fromUser, time, receipt) 
                VALUES (?,?,?,?,?,?,?)
                """, [
                    Uuid().v4().toString(),
                    MessageType.receiptClient,
                    "吃饭了？",
                    Uuid().v4().toString(),
                    Uuid().v4().toString(),
                    DateTime.now().millisecondsSinceEpoch.toString(),
                    1
                  ]);
                },
                child: Text("Db Test")),
            Expanded(
                child: ListView.builder(
              itemBuilder: (context, index) {
                var _model = _list[index];
                print('model: ${_model}');
                return ListTile(
                    title: Text(_model.id),
                    subtitle: Text("${_model.content}, ${_model.time}"));
              },
              itemCount: _list.length,
            ))
          ],
        ),
      ),
    );
  }

  void _onPressed(ApplicationBloc bloc) async {
    List<Map<String, dynamic>> data =
        await bloc.queryDb("select * from t_messages order by time desc");
    List<MessageModel> models =
        data.map((i) => MessageModel.fromJson(i)).toList();

    setState(() {
      models.forEach((m) {
        if (!_list.contains(m)) {
          _list.add(m);
        }
      });
    });
  }
}

class HistoryItemWidget extends StatelessWidget {
  final HistoryModel historyModel;
  final VoidCallback onTap;

  const HistoryItemWidget({this.historyModel, this.onTap});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: onTap,
      key: ObjectKey(historyModel),
      leading: CircleAvatar(
        child: Text(historyModel.avatar),
      ),
      title: Text(historyModel.friendName),
      subtitle: Text(historyModel.lastMsg, overflow: TextOverflow.ellipsis),
      trailing: HistoryTrailing(historyModel.time),
    );
  }
}

class HistoryTrailing extends StatelessWidget {
  final String time;

  const HistoryTrailing(this.time);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Text(time),
        const SizedBox(
          height: 3.0,
        ),
        CircleAvatar(
          radius: 10.0,
          child: Padding(
            padding: const EdgeInsets.all(3.0),
            child: Text(
              "9",
              style: TextStyle(fontSize: 11.0, color: Colors.white),
            ),
          ),
          backgroundColor: Colors.lightGreen,
        ),
      ],
    );
  }
}

class MessageUnread extends StatelessWidget {
  final int num;

  const MessageUnread(this.num);

  @override
  Widget build(BuildContext context) {
    return CircleAvatar(
      radius: 10.0,
      child: Padding(
        padding: const EdgeInsets.all(3.0),
        child: Text(
          num.toString(),
          style: TextStyle(fontSize: 11.0, color: Colors.white),
        ),
      ),
      backgroundColor: Colors.lightGreen,
    );
  }
}
